package com.esender.api.filter.impl;

import com.esender.api.client.BeaconCacheClient;
import com.esender.api.filter.CheckFilter;
import com.esender.common.constant.ApiConstant;
import com.esender.common.constant.CacheConstant;
import com.esender.common.enums.ExceptionEnums;
import com.esender.common.exception.ApiException;
import com.esender.common.model.StandardSubmit;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Set;

@Service(value = "sign")
@Slf4j
public class SignCheckFilter implements CheckFilter {
    private static final int SIGN_START_INDEX = 1;
    private static final String CLIENT_SIGN_INFO = "signInfo";
    private static final String SIGN_ID = "id";
    @Autowired
    private BeaconCacheClient beaconCacheClient;
    @Override
    public void check(StandardSubmit standardSubmit) {
        log.info("【接口模块-校验签名】   校验ing…………");
        String text = standardSubmit.getText();
        if (!text.startsWith(ApiConstant.SIGN_PREFIX) || !text.contains(ApiConstant.SIGN_SUFFIX)){
            log.info("【接口模块-校验签名】   无可用签名 text = {}",text);
            throw new ApiException(ExceptionEnums.ERROR_SIGN);
        }
        // 截取签名
        String sign = text.substring(SIGN_START_INDEX, text.indexOf(ApiConstant.SIGN_SUFFIX));
        if (StringUtils.isEmpty(sign)){
            log.info("【接口模块-校验签名】   无可用签名 text = {}",text);
            throw new ApiException(ExceptionEnums.ERROR_SIGN);
        }

        // 从缓存中查出客户所绑定得签名
        Set<Map> values = beaconCacheClient.smember(CacheConstant.CLIENT_SIGN + standardSubmit.getClientId());
        if (null == values || values.isEmpty()){
            log.info("【接口模块-校验签名】   无可用签名 text = {}",text);
            throw new ApiException(ExceptionEnums.ERROR_SIGN);
        }

        for (Map map:values) {
            if (sign.equals(map.get(CLIENT_SIGN_INFO))){
                standardSubmit.setSign(sign);
                standardSubmit.setSignId(Long.parseLong(map.get(SIGN_ID).toString()));
                log.info("【接口模块-校验签名】   找到匹配的签名 sign = {}",sign);
                return;
            }
        }
        log.info("【接口模块-校验签名】   无可用签名 text = {}",text);
        throw new ApiException(ExceptionEnums.ERROR_SIGN);
    }
}
